package com.vinobase.model.dao;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.vinobase.model.bean.Culture;
import com.vinobase.utils.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Repository;

import java.util.Locale;
import java.util.SortedSet;
import java.util.TreeSet;
 //http://www.codeproject.com/KB/aspnet/LocalizedSamplePart2.aspx#databasedesign
@Repository
public class CultureDao {

    @Autowired
    private ObjectifyFactory objectifyFactory;

    @PreAuthorize("hasRole('Admin')")
    public SortedSet<Culture> getList(){
        Objectify ofy = objectifyFactory.begin();
        SortedSet<Culture> cultures = new TreeSet<Culture>();
        cultures.addAll(ofy.query(Culture.class).list());
        return cultures;
    }

    @PreAuthorize("hasRole('Admin')")
    public void create(Culture culture){
        Objectify ofy = objectifyFactory.begin();
        ofy.put(culture);
    }

    public Culture get(Long cultureId){
        Objectify ofy = objectifyFactory.begin();
        Culture c = ofy.find(Culture.class, cultureId);
        if(c == null) {
            throw new ResourceNotFoundException(cultureId);
        }
        return c;
    }

    @PreAuthorize("hasRole('Admin')")
    public void delete(Long cultureId){
        Objectify ofy = objectifyFactory.begin();
        ofy.delete(Culture.class, cultureId);
    }

    public  Key<Culture> getCultureKey(Locale locale){

        Objectify ofy = objectifyFactory.begin();
        Culture cult = ofy.query(Culture.class ).filter("name",locale.getLanguage()).get();
        if(cult == null)
            cult = ofy.query(Culture.class ).filter("name","en").get();
        Key<Culture> cultureKey = new Key<Culture>(Culture.class,cult.getId());
        return cultureKey;
    }


}
